package insight.chain.validation;

import insight.chain.User;
import insight.chain.annotation.Length;
import insight.chain.annotation.Max;
import insight.chain.annotation.Min;
import insight.chain.exception.ValidatorException;

import java.lang.reflect.Field;


/**
 * @author huu
 * @create 2025-08-25-18:44
 * @description: 校验器类
 * 需求： 1.不管多少个报错都需要收集起来
 *        2.想什么时候停止校验都行
 */
public class validator {
    public void validate(Object bean) throws Exception{
        Class<?> beanClass = bean.getClass();
        for (Field field : beanClass.getDeclaredFields()) {
            field.setAccessible(true);
            //看下面这几个max,min, length
            //拿到属性判断属性注解，再去校验，可以做策略了
//            Max max = field.getAnnotation(Max.class);
//            if(max != null){
//                validateMax(max,field.get(bean));
//            }
//            Max min = field.getAnnotation(Min.class);
//            if(min != null){
//                validateMin(min,field.get(bean));
//            }
//            Length length = field.getAnnotation(Length.class);
//            if(length != null){
//                validateLength(length,field.get(bean));
//            }
            //如果怎么样就调用什么，写成列表或者map
//            Max max = field.getAnnotation(Max.class);
//            if(max != null){
//                new MaxValidatorHandler(max.value()).validate(field.get(bean));
//            }
//            Min min = field.getAnnotation(Min.class);
//            if(min != null){
//                new MinValidatorHandler(min.value()).validate(field.get(bean));
//            }
//            Length length = field.getAnnotation(Length.class);
//            if(length != null){
//                new LengthValidatorHandler(length.value()).validate(field.get(bean));
//            }

            //责任链
            //1.拿到每一个的校验链
            ValidatorChain chain = buliderValidatorChain(field);
            chain.validate(field.get(bean));
        }
    }

    private ValidatorChain buliderValidatorChain(Field field) {
        ValidatorChain chain = new ValidatorChain();
        //这里用工厂如何创建？享元模式
        Max max = field.getAnnotation(Max.class);
        if(max != null){
            chain.addLastHandler(new MaxValidatorHandler(max.value()));
        }
        Min min = field.getAnnotation(Min.class);
        if(min != null){
            chain.addLastHandler(new MinValidatorHandler(min.value()));
        }
        Length length = field.getAnnotation(Length.class);
        if(length != null){
            chain.addLastHandler(new LengthValidatorHandler(length.value()));
        }
        return chain;
    }
}
